package ui;

import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextField;
import com.sun.lwuit.events.FocusListener;
import com.sun.lwuit.layouts.BoxLayout;
import java.util.Date;
import java.util.Calendar;

public class DateField extends Container implements FocusListener {

    private final Calendar cal = Calendar.getInstance();
    TextField txtDay;
    TextField txtMonth;
    TextField txtYear;

    public DateField(String label, Date date) {
        this.setLayout(new BoxLayout(BoxLayout.X_AXIS));
        this.addComponent(new Label(label));
        cal.setTime(date);

        txtDay = new TextField(String.valueOf(cal.get(Calendar.DAY_OF_MONTH)), 2);
        txtDay.setConstraint(TextField.DECIMAL);
        txtDay.setInputMode("123");
        txtDay.setMaxSize(2);
        txtDay.addFocusListener(this);
        this.addComponent(txtDay);
        //this.addComponent(new Label("/"));

        txtMonth = new TextField(String.valueOf(cal.get(Calendar.MONTH) + 1), 2);
        txtMonth.setConstraint(TextField.DECIMAL);
        txtMonth.setInputMode("123");
        txtMonth.setMaxSize(2);
        txtMonth.addFocusListener(this);
        this.addComponent(txtMonth);
        //this.addComponent(new Label("/"));

        txtYear = new TextField(String.valueOf(cal.get(Calendar.YEAR)), 5);
        txtYear.setConstraint(TextField.DECIMAL);
        txtYear.setInputMode("123");
        txtYear.setMaxSize(4);
        txtYear.addFocusListener(this);
        this.addComponent(txtYear);

        txtDay.setNextFocusRight(txtMonth);
        txtDay.setNextFocusDown(txtMonth);
        txtMonth.setNextFocusLeft(txtDay);
        txtMonth.setNextFocusUp(txtDay);
        txtMonth.setNextFocusRight(txtYear);
        txtMonth.setNextFocusDown(txtYear);
        txtYear.setNextFocusLeft(txtMonth);
        txtYear.setNextFocusUp(txtMonth);
    }

    public Date getDate() {
        cal.set(Calendar.YEAR, Integer.parseInt(txtYear.getText()));
        cal.set(Calendar.MONTH, Integer.parseInt(txtMonth.getText()) - 1);
        cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(txtDay.getText()));

        return cal.getTime();
    }

    public boolean isValid() {
        try {
            getDate();
            return true;
        } catch (java.lang.IllegalArgumentException ex) {
            return false;
        }
    }
    String contentsBeforeFocus = "";

    public void focusGained(Component c) {
        TextField txt = (TextField) c;
        contentsBeforeFocus = txt.getText();
        txt.setText("");
    }

    public void focusLost(Component c) {
        TextField txt = (TextField) c;
        if (txt.getText().equals("")) {
            txt.setText(contentsBeforeFocus);
        }
    }
}

